<template>
   <el-dialog :model-value="pwdDialogVisible" title="密码集" width="50%" :show-close="false" top="5%">
     <template #header>
        <div
        class="py-[13px] px-[16px] flex items-center justify-between border-b border-solid border-[#E8E8E8]"
      >
        <span class="text-[18px] font-bold">密码集</span>
        <el-icon @click="closeDialog" class="cursor-pointer"
          ><Close
        /></el-icon>
      </div>
     </template>
      <div class="px-[40px] pb-[32px] tableLine">
        <div class="flex justify-end ">
            <!-- <Button type="disabled" style="width: fit-content; margin-right: 10px;">删除所选</Button> -->
          <Button type="primary" style="width: fit-content;" @click="handleAdd">新增</Button>
        </div>
        <div class="tableLine mt-[20px]">
            
          <el-table
            border
            align="left"
            :data="displayTableData"
            style="width: 100%; margin-bottom: 20px; height: 100%"
            row-key="id"
          >
            <el-table-column type="index" label="序号" width="120" align="center" />
            <el-table-column prop="password" label="密码" align="center">
              <template #default="{ row, $index }">
                <!-- 新增行显示输入框 -->
                <el-input 
                  v-if="row.isNew" 
                  v-model="row.password" 
                  placeholder="请输入密码"
                  style="width: 100%;"
                />
                <!-- 编辑行显示输入框 -->
                <el-input 
                  v-else-if="editingRowId === row.id" 
                  v-model="editingPassword" 
                  placeholder="请输入密码"
                  style="width: 100%;"
                />
                <!-- 普通行显示文本 -->
                <span v-else @dblclick="startEdit(row)" style="cursor: pointer;">{{ row.password }}</span>
              </template>
            </el-table-column>
           
            <el-table-column prop="createdTime" label="操作" width="200" align="center" >
              <template #default="{ row, $index }">
                                 <!-- 新增行显示确定和取消按钮 -->
                 <div v-if="row.isNew" class="table-buttons">
                   <el-link type="primary" :underline="false" @click="handleConfirm(row)">
                     <el-icon><Check /></el-icon> 确定
                   </el-link>
                   <el-link type="primary" :underline="false" @click="handleCancel">
                     <el-icon><CloseIcon /></el-icon> 取消
                   </el-link>
                 </div>
                                 <!-- 编辑行显示确定和取消按钮 -->
                 <div v-else-if="editingRowId === row.id" class="table-buttons">
                   <el-link type="primary" :underline="false" @click="confirmEdit(row)">
                     <el-icon><Check /></el-icon> 修改
                   </el-link>
                   <el-link type="primary" :underline="false" @click="cancelEdit">
                     <el-icon><CloseIcon /></el-icon> 取消
                   </el-link>
                 </div>
                 <!-- 普通行显示编辑和删除按钮 -->
                 <div v-else class="table-buttons">
                   <el-link type="primary" :underline="false" @click="startEdit(row)">编辑</el-link>
                   <el-link type="primary" :underline="false" @click="handleDelete(row)">删除</el-link>
                 </div>
              </template>
            </el-table-column>
            <template #empty>
            <span class="txt">暂无数据</span>
          </template>
          </el-table>
        </div>
        <page
          class="place-self-end"
          :options="options"
          :change="change"
          :handleSizeChange="handleSizeChange"
        ></page>
      </div>
   </el-dialog>
  </template>
  <script setup>
  import dayjs from "dayjs";
  import { onMounted, ref, reactive, computed } from "vue";
  import { Close, Check, Close as CloseIcon } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { Delmessage } from '@/utils/message.js';

  const selectId = ref("");
  const options = reactive({
    total: 0,
    pageSize: 10,
    pageNum: 1,
  });
  const emit = defineEmits(['update:pwdDialogVisible'])
  const { pwdDialogVisible } = defineProps({
    pwdDialogVisible: {
      type: Boolean,
      default: false
    }
  });
  const tableData = ref([]);
  const isAdding = ref(false);
  const editingRowId = ref(null);
  const editingPassword = ref('');
  
  // 计算显示的表格数据，新增行会显示在最顶部
  const displayTableData = computed(() => {
    if (isAdding.value) {
      return [{
        id: 'new_' + Date.now(),
        password: '',
        isNew: true,
        createdTime: ''
      }, ...tableData.value];
    }
    return tableData.value;
  });
  
  // 每页显示个数切换
  const handleSizeChange = (value) => {
    options.pageSize = value;
    queryList();
  };
  // 页码切换
  const change = (val) => {
    options.pageNum = val;
    queryList();
  };
  // tab切换
  const onTabClick = (item) => {
    selectId.value = item.id;
    options.pageNum = 1;
    options.pageSize = 10;
    queryList();
  };
  const onOpen = () => {
    // 这里可能需要根据实际需求调整
    console.log('onOpen');
  };
  
  // 新增按钮点击事件
  const handleAdd = () => {
    if (isAdding.value) return; // 防止重复点击
    isAdding.value = true;
  };

  // 确定按钮点击事件
  const handleConfirm = async (row) => {
    if (!row.password.trim()) {
      ElMessage.warning('请输入密码');
      return;
    }
    
    try {
      // 这里调用新增API
      const [err, res] = await api.getPwdAdd({ password: row.password });
      if (err) return;
      
      // 模拟成功
      ElMessage.success('新增成功');
      
      // 重置状态
      isAdding.value = false;
      
      // 重新获取列表
      queryList();
    } catch (error) {
      ElMessage.error('新增失败');
    }
  };

  // 取消按钮点击事件
  const handleCancel = () => {
    isAdding.value = false;
  };
  
  // 开始编辑
  const startEdit = (row) => {
    if (isAdding.value) return; // 如果正在新增，不允许编辑
    editingRowId.value = row.id;
    editingPassword.value = row.password;
  };

  // 确认编辑
  const confirmEdit = async (row) => {
    if (!editingPassword.value.trim()) {
      ElMessage.warning('密码不能为空');
      return;
    }
    
    try {
      // 这里调用编辑API
      const [err, res] = await api.getPwdRename({ id: row.id, password: editingPassword.value });
      if (err) return;
      
      // 模拟成功
      ElMessage.success('编辑成功');
      
      // 更新本地数据
      row.password = editingPassword.value.trim();
      
      // 重置编辑状态
      editingRowId.value = null;
      editingPassword.value = '';
    } catch (error) {
      ElMessage.error('编辑失败');
    }
  };

  // 取消编辑
  const cancelEdit = () => {
    editingRowId.value = null;
    editingPassword.value = '';
  };

  // 删除
  const handleDelete = (row) => {
    const closeDialog = Delmessage({
      title: "删除确认",
      content: "是否确认删除该密码？",
      submitText: "删除",
      cancel: function () {
        // 取消删除，关闭对话框
        closeDialog();
        console.log('取消删除')
      },
      submit: async function () {
        // 执行删除操作
        try {
          // 这里调用删除API
          const [err, res] = await api.getPwdDelete( row.id);
          if (err) return;
          
          // 模拟删除成功（实际使用时取消注释上面的API调用）
          ElMessage.success('删除成功');
          
          // 删除成功后关闭对话框
          closeDialog();
          
          // 重新获取列表
          queryList();
        } catch (error) {
          console.error('删除失败:', error);
          ElMessage.error('删除失败');
        }
      }
    });
  };
  
  // 获取数据列表
  const queryList = async () => {
    console.log('queryList');
    // 模拟数据，实际应该调用API
    let [err, res] = await api.getPwdList({
      current: options.pageNum,
      size: options.pageSize,
    });
    if (err) return;
    tableData.value = res.data.records;
    options.total = res.data.total;
    
    // 模拟数据
    // tableData.value = [
    //   { id: 1, password: 'password123', createdTime: '2024-01-01 10:00:00' },
    //   { id: 2, password: 'password456', createdTime: '2024-01-02 11:00:00' }
    // ];
    // options.total = 2;
  };
  const getDate = (value) => {
    return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
  };
  const getTotal = async () => {
    // 这里需要根据实际API调整
    console.log('getTotal');
    // let [err, res] = await api.getNumber(caseId);
    // if (err) return;
  };
  // 关闭密码集弹窗
  const closeDialog = () => {
    // 关闭弹窗时重置所有状态
    isAdding.value = false;
    editingRowId.value = null;
    editingPassword.value = '';
    emit('update:pwdDialogVisible', false);
  };
  onMounted(() => {
    // if(caseId.value) getTotal();
    console.log('mounted');
    queryList()
  });
 
  
  </script>
  <style lang="scss" scoped>
  .tableLine {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  :deep(.el-drawer__body) {
    padding: 0 !important;
    display: flex !important;
    flex-direction: column;
  }
  .dataItem {
    cursor: pointer;
    margin-right: 12px;
    padding: 4px 16px;
    border: 1px solid rgba(221, 221, 221, 1);
    border-radius: 4px;
    background: rgba(255, 255, 255, 1);
    &.active {
      border: none;
      color: #fff;
      background: rgba(26, 102, 255, 1);
    }
  }
  .dataItem:last-of-type {
    margin-right: 0;
  }
  .sussess {
    margin-right: 8px;
    width: 10px;
    height: 10px;
    border-radius: 20px;
    background: rgba(19, 194, 49, 1);
  }
  .fail {
    margin-right: 8px;
    width: 10px;
    height: 10px;
    border-radius: 20px;
    background: rgba(224, 27, 43, 1);
  }
  
     // 操作栏按钮样式
   .table-buttons {
     display: flex;
     justify-content: center;
     gap: 16px;

     .el-link {
       font-size: 14px;
       text-decoration: none;

       &:hover {
         text-decoration: none;
       }
     }

     .el-icon {
       color: #1A66FF;
       margin-right: 4px;
       font-size: 16px;
     }
   }
  
  </style>
  
  